// 定义网络图转base64的方法
function getBase64(url, ext, callback) {
  return new Promise((resolve, reject) => {
    var canvas = document.createElement("canvas");   //创建canvas DOM元素
    var ctx = canvas.getContext("2d");
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.src = url;
    img.onload = function () {
      canvas.width = img.width; //指定画板的宽度，自定义
      canvas.height = img.height; //指定画板的高度,自定义
      ctx.drawImage(img, 0, 0, img.width, img.height); //参数可自定义
      let dataURL = canvas.toDataURL("image/" + ext);
      canvas = null;
      resolve(dataURL)
    };
  })
}

// 定义base64转文件流的方法
function dataURLtoBlob(dataurl) {
  return new Promise((resolve, reject) => {
    let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    resolve(new Blob([u8arr], {type: mime}))
  })
}

//将blob转换为file
function blobToFile(theBlob, fileName) {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}

// 正则处理赋值内容
function matchStr(html, newHtml = '') {
  let relImg = /<img[\s\S]*?src\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/
  let matchObj = html.match(relImg)

  // console.log(matchObj);

  if (!matchObj) return newHtml
  else {
    let startIndex = matchObj.index
    let endIndex = matchObj.index + matchObj[0].length

    let startString = html.substring(0, startIndex)
    let endString = html.substring(endIndex)

    // console.log(matchObj[0].length,startIndex,endIndex);

    if (matchObj[0].indexOf('dictionaries_url') === -1) {

      let htmlStr = `<div contenteditable="false">
                        <div class="pgc-image pgc-card-fixWidth">
                          <div class="pgc-img-wrapper">
                          <img src=""  dictionaries_url="${matchObj[1]}">
                              <div class="editor-image-menu">
                              <div class="editor-image-menu-bg"></div>
                              <div class="image-menu-event-prevent"><a class="editor-image-menu-item ">编辑</a></div>
                            </div>
                            <span class="ttcore-remove-blot"></span>
                           </div>
                          </div>
       </div> `

      newHtml += startString + htmlStr
      // console.log(newHtml);
      return matchStr(endString, newHtml)

    } else {
      return matchStr(endString, newHtml)
    }
  }
}

// 创建自定义的图片文本格式
function newImgEl(src) {
  let addImg = document.createElement('div')
  addImg.innerHTML = `<div class="pgc-image pgc-card-fixWidth">
                              <div class="pgc-img-wrapper">
                              <img src=""  dictionaries_url="${src}">
                                  <div class="editor-image-menu">
                                  <div class="editor-image-menu-bg"></div>
                                  <div class="image-menu-event-prevent"><a class="editor-image-menu-item ">编辑</a></div>
                                </div>
                                <span class="ttcore-remove-blot"></span>
                               </div>
                              </div>`

  addImg.setAttribute("contenteditable", "false");
  return addImg
}


// dom处理粘贴各种数据
function matchImg(content, el = false) {
  // 创建一个容器
  let div
  if (el) div = el
  else {
    div = document.createElement('div')
    div.innerHTML = content
  }


  for (let item of div.children) {

    console.dir(item);
    if (item.tagName === "IMG") {
      div.replaceChild(newImgEl(item.src), item)
    } else {
      let imgArr = item.querySelectorAll('img')

      if (imgArr.length === 1) {
        let whiteListIndex = whiteList.findIndex((val) => {
          return imgArr[0].src.indexOf(val) !== -1
        })

        console.log(whiteListIndex);
        if (Number(whiteListIndex) !== -1) continue


        div.replaceChild(newImgEl(imgArr[0].src), item)
      } else if (imgArr.length > 1) {
        matchImg('', item)
      }
    }
  }

  return div.innerHTML
}

// 上传图片封装
async function  updateImg (base64) {
  let response = await instance.get('file/attachment/getPostObject?fileName=file')

  response = response.data

  let data = response.data.postObject
  let upUrl = response.data.urlStr

  editor.customConfig.uploadImgServer = response.data.urlStr
  editor.customConfig.uploadImgParams = response.data.postObject
  editor.customConfig.uploadImgHeaders = {
    'accessToken': 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0MDYwMDQwIiwiaWF0IjoxNTgyNjMyNTY2LCJzdWIiOiJkc2tqMiIsImlzcyI6ImRza2oxIiwiZXhwIjoxNjE0MTY4NTY2fQ.CCcMQvNetTESB-hnHBJgQEreO8sya-1I8L91v4TJxcA'
  }

  let base641 = base64
  console.log(base641);
  return new Promise((resolve, refuse) => {
    ajax({
      headers: {'accessToken': 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0MDYwMDQwIiwiaWF0IjoxNTgyNjMyNTY2LCJzdWIiOiJkc2tqMiIsImlzcyI6ImRza2oxIiwiZXhwIjoxNjE0MTY4NTY2fQ.CCcMQvNetTESB-hnHBJgQEreO8sya-1I8L91v4TJxcA'},
      withCredentials: false,
      file: base641,
      data,
      filename: 'file',
      action: upUrl,
      onProgress: e => {
        // this.handleProgress(e, file);
      },
      onSuccess: res => {
        console.log(res.data.url);
        resolve(res.data.url)
      },
      onError: (err, response) => {
        console.log(err, response)
      }
    })
  })
}

// 获取DOM附近相邻的元素
function siblings(elm) {
  console.log(elm);
  let arr = [];
  let siblingsArr = elm.parentNode.children;

  for (let item of siblingsArr) {
    if (item !== elm) {
      console.log(item, elm);
      arr.push(item)
    }
  }

  return arr
}

// 处理是否激活class
function disposeActive(elm) {
  elm.classList.add("active");

  siblings(elm).forEach(function (item) {
    item.classList.remove('active')
  })
}

function returnCropperBlob() {
  return new Promise((resolve, reject) => {
    cropper.getCroppedCanvas().toBlob(function (blob) {
      resolve(blob)
    })

  })
}



